<?php defined('SYSPATH') or die('No direct script access.');

class email extends email_Core {
	
	public static $ERROR = 0;
	public static $NOT_SENT_BY_CONFIG = 1;
	public static $SUCCESS = 2;

    public static function sendInUtf8($toName, $toEmail, $subject, $message, $isHtml = FALSE) {
        if (Kohana::config('yosemin.sendingEmailsEnabled')) {
            $fromName = Kohana::config('yosemin.email_from_name');
            $fromEmail = Kohana::config('yosemin.email_from');
            if ($fromName) {
                $from = '=?UTF-8?B?' . base64_encode($fromName) . '?= <' . $fromEmail . '>';
            }
            if ($toName) {
                $to = '=?UTF-8?B?' . base64_encode($toName) . '?= <' . $toEmail . '>';
            }
            $header = 'MIME-Version: 1.0' .
                    "\r\n" . 'Content-type: ' . ($isHtml ? 'text/html' : 'text/plain') . '; charset=UTF-8' . "\r\n" .
                    'From: ' . $from . "\r\n";
            
            $result = mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $message, $header);
            if (! $result) {
            	Kohana::log('error', 'Error sending email to: "' . $toName . '<' . $person['email'] . '>" subject: "' . $subject . '".');
            	Messages::instance()->error('application-email-sendingFailed', $toName);
            	return self::$ERROR;
            }
            Kohana::log('info', 'Email sent to: "' . $toName . '<' . $person['email'] . '>" with subject: "' . $subject . '".');
            return self::$SUCCESS;
        }
        if (! IN_PRODUCTION) {
        	Messages::instance()->info($subject);
        	Messages::instance()->info($message);
        }
        return self::$NOT_SENT_BY_CONFIG;
    }
    
    public static function emailHeading($person, $languageCode) {
    	if ($languageCode == 'en') {
    		return text::getInLang($languageCode, 'common-email-heading', $person['first_name']);
    	}
    	return text::getInLang($languageCode, 'common-email-heading', $person['first_name']);
    }
    
    public static function emailClosing($languageCode) {
    	return text::getInLang($languageCode, 'common-email-closing');
    }
    
    public static function addHeadingAndClosing($body, $person, $languageCode=null) {
    	if (! $languageCode) {
    		$languageCode = $person['preferred_language'];
    	}
    	return self::emailHeading($person, $languageCode) . $body . self::emailClosing($languageCode);
    }
}
